﻿using AutoMapper;
using FarmSmartSleep.Common.Domain.BeginTable;
using FarmSmartSleep.Common.Domain.PM;
using FarmSmartSleep.Common.Dtos;
using FarmSmartSleep.Common.Infrastructure;
using MediatR;

namespace FarmSmartSleep.Organ.API.Application.ProductionManagement.SheepTransferCommands
{
    public class SheepTransferCreateHander : IRequestHandler<SheepTransferCreateComand, Result>
    {

        private readonly IBaseRepository<SheepTransfer> baseRepository;
        private readonly IBaseRepository<SleepInfor> sleepRaseRepository;
        private readonly ILogger<SheepTransferCreateHander> logger;
        private readonly IMapper mapper;

        public SheepTransferCreateHander(IBaseRepository<SheepTransfer> baseRepository, ILogger<SheepTransferCreateHander> logger, IMapper mapper, IBaseRepository<SleepInfor> sleepRaseRepository)
        {
            this.baseRepository = baseRepository;
            this.logger = logger;
            this.mapper = mapper;
            this.sleepRaseRepository = sleepRaseRepository;
        }

        /// <summary>
        /// 添加羊只转舍信息
        /// </summary>
        /// <param name="request">添加羊只转舍信息强求对象</param>
        /// <param name="cancellationToken">允许异步</param>
        /// <returns>添加羊只转舍信息响应对象</returns>
        public async Task<Result> Handle(SheepTransferCreateComand request, CancellationToken cancellationToken)
        {
            try
            {
                var result = new Result();
                SheepTransfer sheepTransfer = mapper.Map<SheepTransfer>(request);
                sheepTransfer.CreateTime = DateTime.Now;
                result.Code = await baseRepository.AddAsync(sheepTransfer);

                SleepInfor sleepInfor = sleepRaseRepository.GetAll().FirstOrDefault(c => c.SleepInforId == request.EarNo);
                if (sleepInfor != null)
                {
                    sleepInfor.RecordcottageId = sheepTransfer.TransferBarn;
                    sleepInfor.FieIdId = sheepTransfer.TransferPen;
                    result.Code += sleepRaseRepository.Update(sleepInfor);
                }

                return result;

            }
            catch (Exception ex )
            {
                logger.LogError("添加羊只转舍信息方法调用出错" + ex);
                throw;
            }
        }
    }
}
